import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/index',
    name: 'index',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import('../views/Index.vue'),
    redirect: '/index/noteEditor',
    children: [
      {
        path: 'noteEditor',
        name: 'noteEditor',
        component: () => import('../views/NoteEditor.vue'),
      },
      {
        path: "noteList",
        name: "noteList",
        component: () => import('../views/note-list/NoteList.vue'),
      },
      {
        path: 'folder',
        name: 'folder',
        component: () => import('../views/file/folder.vue'),
      },
      {
        path: 'fileResource',
        name: 'fileResource',
        component: () => import('../views/file/fileResource.vue'),
      },
    ]
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('../views/registerAccount.vue')
  }
]


const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  Vue.prototype.$previousRoute = from;
  if (to.path === '/') return next();
  let user = JSON.parse(sessionStorage.getItem('user') ? sessionStorage.getItem('user') : "{}");
  let shareNoteId = to.path.indexOf('shareNoteId') > -1 ? to.path.split('shareNoteId=')[1] : null;
  if (shareNoteId) {
    sessionStorage.setItem('shareNoteId', shareNoteId);
    return next({path: '/index/noteEditor', query: {shareNoteId}})
  }
  if (to.path !== '/' && !user?.userId && !to.query?.shareNoteId) {
    return next({path: '/'})
  } else {
    next();
  }
});

export default router
